using Microsoft.Xna.Framework.Graphics;

namespace BlobSim.Shapes
{
    class Cube : Shape
    {
        #region Private Data

        private GraphicsDevice _device;
        private VertexBuffer _vertexBuffer;
        private IndexBuffer _indexBuffer;

        private float _size;
        private int _segments;

        #endregion

        #region Constructor

        public Cube(GraphicsDevice device, float size, int segments)
        {
            _device = device;

            _size = size;
            _segments = segments;

            BuildCube();
        }

        #endregion

        #region Overrides

        public override VertexBuffer VertexBuffer { get { return _vertexBuffer; } }
        public override IndexBuffer IndexBuffer { get { return _indexBuffer; } }

        public override void Draw()
        {
            for (int f = 0; f < 6; f++)
            {
                int faceBaseIdx = f * _segments * 2 * (_segments + 1);
                for (int s = 0; s < _segments; s++)
                {
                    _device.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0,
                        2 * (_segments + 1),
                        faceBaseIdx + s * 2 * (_segments + 1),
                        2 * _segments);
                }
            }
        }

        #endregion

        #region Private Implementation

        private void BuildCube()
        {
            VertexPositionNormalTexture[] vertices;
            ushort[] indices;
            Utils.BuildCube(_size, _segments, out vertices, out indices);

            _vertexBuffer = new VertexBuffer(_device, typeof(VertexPositionNormalTexture), vertices.Length, BufferUsage.None);
            _vertexBuffer.SetData(vertices);
            _indexBuffer = new IndexBuffer(_device, typeof(ushort), indices.Length, BufferUsage.None);
            _indexBuffer.SetData(indices);
        }

        #endregion
    }
}
